﻿#pragma once

#include <qrunnable.h>
#include <qobject.h>
#include <qthreadpool.h>

class FileReader1 :public QObject, public QRunnable
{
  Q_OBJECT

private:
  QString filePath = "";

  friend class FileReader;
signals:
  void signal_FileData(QString filePath, QByteArray data);
  void signal_openFileFailed(QString filePath);

private:
  FileReader1(QString filePath);
  ~FileReader1();
public:
  void run();
};

class FileReader : public QObject
{
private:
  QThreadPool* qThreadPool = Q_NULLPTR;
public:
  FileReader(QObject* parent = Q_NULLPTR);
  ~FileReader();

public:
  template<class FileDataUser>
  void readFromFile(QString filePath, FileDataUser* fileDataUser, void(FileDataUser::* handleFileData)(QString, QByteArray), void(FileDataUser::* handleFileOpenFailed)(QString) = Q_NULLPTR)
  {
    FileReader1* fileReader1 = new FileReader1(filePath);
    fileReader1->setAutoDelete(true);
    if (Q_NULLPTR != handleFileData)
      {
        connect(fileReader1, &FileReader1::signal_FileData, fileDataUser, handleFileData, Qt::QueuedConnection);
      }
    if (Q_NULLPTR != handleFileOpenFailed)
      {
        connect(fileReader1, &FileReader1::signal_openFileFailed, fileDataUser, handleFileOpenFailed, Qt::QueuedConnection);
      }
    qThreadPool->start(fileReader1);
  }
public:
  QThreadPool* getQThreadPool();
  void setQThreadPool(QThreadPool* qThreadPool);
};
